#include "rtc.h"

#include "Wire.h"                // I2C para el reloj
#include "util.h"                // General purpose functions

#include <stdio.h>

#ifdef __PC__
  #include <time.h>       /* time_t, struct tm, time, localtime */
#endif


// Convert normal decimal numbers to binary coded decimal (RTC)
byte decToBcd(byte val)
{
 return ( (val/10*16) + (val%10) );
}

// Convert binary coded decimal to normal decimal numbers (RTC)
byte bcdToDec(byte val)
{
 return ( (val/16*10) + (val%16) );
}




static char ascTimeBuffer[8];

char* getTimeHHMM()
// Leer la hora                        
{
	Wire.beginTransmission( DS1307_I2C_ADDRESS);
    Wire.write( (byte)0x00);
    Wire.endTransmission();

	Wire.requestFrom( DS1307_I2C_ADDRESS, 7);
    int second = bcdToDec( Wire.read() & 0x7f);    // Lee secuencialmente, si no se leen los segundos toma mal los valores de hora y minuto
    int minute = bcdToDec( Wire.read());
	int hour   = bcdToDec( Wire.read() & 0x3f);  // Need to change this if 12 hour am/pm

	sprintf( ascTimeBuffer, "%02d%02d", hour, minute);
#ifdef __PC__
	time_t rawtime;
	struct tm * timeinfo;

	time (&rawtime);
	timeinfo = localtime ( &rawtime);
	sprintf( ascTimeBuffer, "%02d%02d", timeinfo->tm_hour, timeinfo->tm_min);
#endif
 	return ascTimeBuffer;
}


void setDateDs1307()                
/* * Commands:
   * T(00-59)(00-59)(00-23)(1-7)(01-31)(01-12)(00-99) - T(sec)(min)(hour)(dayOfWeek)(dayOfMonth)(month)(year) -
   * T - Sets the date of the RTC DS1307 Chip.
   * Example to set the time for 25-Jan-2012 @ 19:57:11 for the 4 day of the week, use this command - T1157194250112
   * Q(1-2) - (Q1) Memory initialization  (Q2) RTC - Memory Dump  
   * R - Read/display the time, day and date*/
{
/*
  int second = (byte) ((Serial.read() - 48) * 10 + (Serial.read() - 48)); // Use of (byte) type casting and ascii math to achieve result.  
  int minute = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
  int hour  = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
  int dayOfWeek = (byte) (Serial.read() - 48);
  int dayOfMonth = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
  int month = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
  int year= (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
  Wire.beginTransmission( DS1307_I2C_ADDRESS);
  Wire.write( 0x00);
  Wire.write( decToBcd( second) & 0x7f);    // 0 to bit 7 starts the clock
  Wire.write( decToBcd( minute));
  Wire.write( decToBcd( hour));      // If you want 12 hour am/pm you need to set
                                  // bit 6 (also need to change readDateDs1307)
  Wire.write( decToBcd( dayOfWeek));
  Wire.write( decToBcd( dayOfMonth));
  Wire.write( decToBcd( month));
  Wire.write( decToBcd( year));
  Wire.endTransmission();
*/
}

